import 'dart:async';
import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:imclient/imclient.dart';
import 'package:pin_code_fields/pin_code_fields.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../TabBar/TabbarView.dart';
import '../http/NoLoadingGetApi.dart';
import '../http/api.dart';
import '../http/getapi.dart';
import 'LoginVIewController.dart';


class SMSView extends StatelessWidget {
  const SMSView({super.key, required this.phoneNumber, required this.validCodeReqNo });
  final String phoneNumber;
  final String validCodeReqNo;

  @override
  Widget build(BuildContext context) {
    Timer _timer;
    int curentTimer =60;


    return Scaffold(
      appBar: AppBar(

        backgroundColor: Colors.white10,
        leading: IconButton(

          onPressed: (){
            Navigator.of(context).pop(
                MaterialPageRoute(builder: (builder) {
                  return LoginVC();
                }));
          },
          icon: Icon(Icons.close,size: 30.w,),
        ),
      ),
      body: ListView(

        children: [
          SizedBox(height: 30.h,),
          Container(
            height: 30.h,

            margin: EdgeInsets.only(left: 30.h),
            alignment: Alignment.centerLeft,
            child:  Text("请输入验证码",style: TextStyle(color: Color.fromRGBO(231, 112, 27, 0.85),fontSize: 26.sp,fontWeight: FontWeight.w600),),
          ),
          Container(
            height: 30.h,
            margin: EdgeInsets.only(left: 30.h),
            alignment: Alignment.centerLeft,
            child: Row(
              children: [
                Text("验证码已发送至  ",style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1),fontSize: 14.sp,)),
                Text(phoneNumber,style: TextStyle(color: Colors.black,fontSize:14.sp,fontWeight: FontWeight.w600),),


              ],

            ),
          ),
          SizedBox(
            height: 30,
          ),

          TimerCode(phoneNumber: phoneNumber,validCodeReqNo:validCodeReqNo,),
        ],
      ),
    );
  }
}

class TimerCode extends StatefulWidget {
  final String phoneNumber;
  final String validCodeReqNo;
  const TimerCode({super.key, required this.phoneNumber, required this.validCodeReqNo});

  @override
  State<TimerCode> createState() => _TimerCodeState();
}

class _TimerCodeState extends State<TimerCode> {
  late Timer _timer;
  int curentTimer=60;
  bool isTimerRunning = false;
  String validCodeReqNo ="";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    startTimer();
  }

  void startTimer() {
    setState(() {
      curentTimer = 60;
      isTimerRunning = true; // 设置定时器正在运行
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        curentTimer--;
        if (curentTimer == 0) {
          _timer.cancel();
          isTimerRunning = false; // 定时器结束后设置为非运行状态
          print("Timer ended");

          if (mounted) {
            setState(() {}); // 刷新状态以使按钮可点击
          }
        }
        if (!mounted) {
          _timer.cancel(); // 防止在组件被销毁后仍然运行定时器
        }
        setState(() {});
      });
    });
  }
  TextEditingController _controller = TextEditingController();

  void getUserDetail(String token){
    NoLoadinggetApiManager.getData(
      context, // 上下文对象，用于显示提示信息等
      MyServiceUrl.getLoginUser, // 您的API端点
      {}, // 查询参数，如果没有可以传递null
          (responseData) async {
        await UserIdManager.saveUserID(responseData['data']['id'].toString());
        await PhoneNumManager.savePhone(responseData['data']['phoneNum'].toString());
        Navigator.of(context).pushAndRemoveUntil(
            MaterialPageRoute(builder: (builder) {
              return TabbarView(pateIndex: 0,);
            }), (route) => route == null);
      },
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _timer.cancel();

  }
  @override
  Widget build(BuildContext context) {
    return   Column(
      children: [
        Container(
          margin: EdgeInsets.only(left: 50.w,right: 50.w),
          child: PinCodeTextField(
              appContext: context,//context
              length: 4,//输入的长度
              controller: _controller,
              autoFocus: true,

              textStyle:TextStyle(color: Colors.black),
              cursorColor: Colors.black,
              pinTheme: PinTheme(
                shape: PinCodeFieldShape.box, //输入框的形状
                borderRadius: const BorderRadius.all(Radius.circular(10)),
                activeColor:Colors.black,
                selectedColor:Colors.black,
                inactiveColor:Colors.black26,
              ),
              keyboardType: TextInputType.number,
              onChanged: (value)  async {
                print("onchange $value");
                await TokenManager.saveToken("");
                if(value.length==4){
                  print(validCodeReqNo);
                  ApiManager.postData(
                    context,
                    'api/auth/auth/shipper/doLoginByPhone',
                    {
                      "phone": widget.phoneNumber,
                      "validCode":value,
                      "device": 'APP',
                      "codeType":"LOGIN",
                      "validCodeReqNo":validCodeReqNo!=""?validCodeReqNo: widget.validCodeReqNo,
                      "platform":2,
                      // 'clientId':await Imclient.clientId,
                      'clientId':"123129391239",
                    },
                        (responseData) async {

                      print(responseData);
                      await TokenManager.saveToken(responseData['data']['token'].toString());
                      String token =responseData['data']['token'].toString();
                      await IMIdManager.saveIMID(responseData['data']['imToken']);
                      getUserDetail(token);

                    },
                  );


                }
              }
          ),
        ),
        SizedBox(height: 10.h,),
        curentTimer!=0?
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(width: 40.w,),
            Text(curentTimer.toString() +"s后可重新获取验证码",style: TextStyle(color: MyColors.hintColor),),
          ],
        ):GestureDetector(
          child:  Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              SizedBox(width: 40.w,),
              Text("重新获取验证码",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
            ],
          ),
          onTap: (){
            startTimer();
            if (isTimerRunning){

              String phoneNum = widget.phoneNumber;
              getApiManager.getData(
                context, // 上下文对象，用于显示提示信息等
                'api/auth/auth/shipper/getPhoneValidCode', //您的API端点
                {"phone":phoneNum,"codeType":"LOGIN"}, // 查询参数，如果没有可以传递null
                    (responseData) async {
                  BrnToast.show(
                    "发送成功",
                    context,
                    duration: BrnDuration.short,
                  );
                  setState(() {
                    validCodeReqNo=responseData['data']['validCodeReqNo'];
                  });
                },
              );

            }
          },
        ),
    //     SizedBox(height: 20.h,),
    //     Container(
    //     height: 40.h ,
    //     margin: EdgeInsets.only(left: 30.w,right: 30.w),
    //     decoration: BoxDecoration(
    //         color: curentTimer > 0?Color.fromRGBO(223, 223, 223, 1):Color.fromRGBO(231, 112, 27, 0.85),
    //         borderRadius: BorderRadius.all(Radius.circular(30))),
    //
    //     width: double.infinity,
    //
    //
    //     child: TextButton(
    //
    //       child: Text("获取短信验证码",style: TextStyle(color: Colors.white,fontSize: 14.sp),),
    //       onPressed:curentTimer==0?(){
    //         if(curentTimer==0) {
    //           startTimer();
    //           if (isTimerRunning){
    //
    //             String phoneNum = widget.phoneNumber;
    //             getApiManager.getData(
    //               context, // 上下文对象，用于显示提示信息等
    //               'api/auth/auth/shipper/getPhoneValidCode', // 您的API端点
    //               {"phone":phoneNum,"codeType":"LOGIN"}, // 查询参数，如果没有可以传递null
    //                   (responseData) async {
    //                 BrnToast.show(
    //                   "发送成功",
    //                   context,
    //                   duration: BrnDuration.short,
    //                 );
    //                 setState(() {
    //                   validCodeReqNo=responseData['data']['validCodeReqNo'];
    //                   print(validCodeReqNo);
    //                 });
    //               },
    //             );
    //           }
    //         }
    //
    //       }:null,
    //
    //
    //
    //
    //
    //
    //     )
    // ),
      ],
    );

  }
}



